<!-- toc -->
<script setup>

import { onMounted, onUnmounted, ref } from 'vue'
const props = defineProps({ tocLinks: Array })

function scrollTo(id) {
  const element = document.getElementById(id)
  if (element == null) return
  let targetPosition = element.getBoundingClientRect().top + window.scrollY
  window.scrollTo({
    top: targetPosition - 30,
    behavior: 'smooth'
  })
}

onMounted(() => { window.addEventListener('scroll', onScroll) })
onUnmounted(() => { window.removeEventListener('scroll', onScroll) })

const currentActive = ref('h-1-0')

function onScroll() {
  for (const item of props.tocLinks) {
    const element = document.getElementById(item.id)
    if (element == null) return
    const rect = element.getBoundingClientRect()
    if (rect.top <= 50 && rect.bottom >= 50) {
      currentActive.value = item.id
      break
    }
  }
}

const getIndex = id => '-'.repeat(id.split('-')[1] - 1)
</script>

<template>
  <div class="toc-wrapper invisible-scrollbar">
    <ul class="toc-list">
      <li v-for="link in tocLinks" :key="link.id" class="toc-link" :class="{ 'toc-active': currentActive === link.id }">
        <a :href="`#${link.id}`" @click.prevent="scrollTo(link.id)">
          {{ getIndex(link.id) + link.title }}
        </a>
      </li>
    </ul>
    <div class="toc-end">
      <a href="#" @click.prevent="scrollTo('article-footer')">
        {{ $t('view_article.toc_end') }}
      </a>
    </div>
  </div>
</template>

<style scoped lang="scss">
.toc-wrapper {

}

.invisible-scrollbar::-webkit-scrollbar {
  display: none;
}

.toc-list {
  list-style: none;
  font-weight: 2rem;
}

.toc-link {
  border-left: 2px solid #8fc7f29f;
  text-decoration: none;
  padding-left: 5px;

  &:hover {
    border-left: 2px solid #9e5b0b;
  }
}

.toc-link a {
  color: #647c6b;
  padding: 5px;
  font-weight: 600;
  line-height: 2rem;
  width: 100%;
  height: 100%;
  display: block;

}

.toc-end {
  margin-top: 10px;
  text-decoration: none;

  &:hover {
    text-decoration: underline;
  }
}

.toc-active {
  border-left-color: #006b83;

  & a {
    color: #1f6c00;
  }
}
</style>
